package com.example.controller;

import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@ControllerAdvice
public class ControllerExceptionHandler {
    private static final Logger log = Logger.getLogger(ControllerExceptionHandler.class);

//    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest request){
        request.setAttribute("exception",e);
        log.error(e);
        return "error";
    }

//    @ExceptionHandler(value = {RuntimeException.class})
    @ResponseBody
    public String handlerException2(RuntimeException e){
        Gson gson = new Gson();
        HashMap<String,Object> map = new HashMap<>();
        map.put("success",false);
        map.put("message",e.getMessage());
        String json = gson.toJson(map);
        return json;
    }

    @ExceptionHandler(value = {RuntimeException.class})
    @ResponseBody
    public Object handlerException3(RuntimeException e){
        HashMap<String,Object> map = new HashMap<>();
        map.put("success",false);
        map.put("message",e);
        return map;
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Object exceptionHandler(BindException e) {
        HashMap<String,Object> map = new HashMap<>();
        map.put("success",false);
        map.put("message",e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        log.error("校验异常："+ e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return map;
    }
}
